package com.crazymaker.springcloud.cloud.center.zuul.config;

import com.crazymaker.springcloud.common.constants.SessionConstants;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
@Slf4j
public class ModifyRequestHeaderFilter extends ZuulFilter
{

    @Override
    public boolean shouldFilter()
    {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String uri = request.getRequestURI();
        /**
         * 根据条件去判断是否需要路由，是否需要执行该过滤器
         */
        String token = request.getHeader(SessionConstants.AUTHORIZATION_HEAD);
//        log.info("token=" + token);
        if (!StringUtils.isEmpty(token))
        {
            return true;
        }

        token = request.getHeader(SessionConstants.B_AUTHORIZATION_HEAD);
//        log.info("token=" + token);
        if (!StringUtils.isEmpty(token))
        {
            return true;
        }
        return false;
    }

    /**
     * 修改请求头
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException
    {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String sessionSeed = (String) request.getAttribute(SessionConstants.SESSION_SEED_HEAD);
        ctx.addZuulRequestHeader(SessionConstants.SESSION_SEED_HEAD, sessionSeed);
        return null;
    }

    @Override
    public String filterType()
    {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder()
    {
        return 1;
    }

}
